package com.tools.cleanmaster.receiver;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.CleanConstant;
import com.tools.cleanmaster.manager.NotificationSceneManager;
import com.tools.cleanmaster.scenenew.SceneToolkit;
import com.tools.cleanmaster.store.SceneSharedPrefManager;
import com.tools.cleanmaster.ui.notification.NotificationBaseItem;
import com.tools.cleanmaster.ui.notification.item.CpuCoolerItem;
import com.tools.cleanmaster.ui.notification.item.TotalMemoryUsageItem;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;


public class ScenePeriodTaskReceiver extends BroadcastReceiver {
    public static final String TAG = "NotificationBaseItem";
    public static final String ACTION_SCENE_REALTIME_TASK = CleanConstant.REAL_PACKAGE_NAME + ".action.realtimetask";
    private static final int SCENE_REALTIME_LAPSE_MS = 5 * 60 * 1000;

    private ScenePeriodTaskReceiver() {
    }

    private static ScenePeriodTaskReceiver sInstance;

    public static ScenePeriodTaskReceiver getInstance() {
        if (sInstance == null) {
            synchronized (ScenePeriodTaskReceiver.class) {
                if (sInstance == null) {
                    sInstance = new ScenePeriodTaskReceiver();
                    sInstance.init();
                }
            }
        }
        return sInstance;
    }

    private Context mContext;
    private AtomicBoolean mRegisterFlag = new AtomicBoolean(false);

    private void init() {
        mContext = CleanApplication.getInstance();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_SCENE_REALTIME_TASK.equals(action)) {
            realTimeScan();
        }
    }

    public synchronized void start() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_SCENE_REALTIME_TASK);
        mContext.registerReceiver(this, filter);

        scheduleTask(ACTION_SCENE_REALTIME_TASK);
        mRegisterFlag.set(true);
    }

    public synchronized void stop() {
        if (mRegisterFlag.getAndSet(false)) {
            mContext.unregisterReceiver(this);
        }
    }

    /**
     * 场景点检测调度
     */
    private void scheduleTask(String sType) {
        if (SceneSharedPrefManager.getSceneRestartTime() != 0) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.d(TAG, "场景化检测已经停止，无需再安排检查任务 " + sType);
            }
            return;
        }
        final Intent taskIntent = new Intent();
        long delayTime = SCENE_REALTIME_LAPSE_MS;
        if (ACTION_SCENE_REALTIME_TASK.equals(sType)) {
            delayTime = SCENE_REALTIME_LAPSE_MS;
        }
        taskIntent.setAction(sType);
        NotificationSceneManager.getInstance().postDelayed(new Runnable() {
            @Override
            public void run() {
                mContext.sendBroadcast(taskIntent);
            }
        }, delayTime);
    }

    /**
     * 实时扫描场景点
     */
    private void realTimeScan() {
        scheduleTask(ACTION_SCENE_REALTIME_TASK);

        if (FeatureConfig.DEBUG_LOG) {
            LogHelper.d(TAG, "场景化实时触发类型,检查开始");
        }
        if (!NotificationSceneManager.getInstance().checkAndRestTimeLimit()) {
            return;
        }
        final int memPercent = SceneToolkit.calcMemoryUsedPercent();
        List<NotificationBaseItem> realTimeScanItemList = new ArrayList<NotificationBaseItem>() {
            {
                add(new TotalMemoryUsageItem(memPercent));
                add(new CpuCoolerItem());
            }
        };
        for (NotificationBaseItem item : realTimeScanItemList) {
            if (item.checkRules()) {
                NotificationSceneManager.getInstance().showSceneNotification(item);
                break;
            }
        }
    }


}
